#include <iostream>
#include <algorithm>
#include <vector>
#include <mongo/client/dbclient.h>

using namespace mongo;
using namespace std;
template<typename T>
void print(vector<T> &arr)
{
    size_t length = arr.size();
    for (size_t i = 0; i != length; ++i) {
        std::cout << arr.at(i) << '\n';
    }
}
void getBoolSearchRet(const vector<int> &terms, vector<int> &ret,
        const std::string mongodbCollection="ask.ageId_488",
        const std::string host="localhost"); 


int main() {
    try {
        vector<int> terms;
        terms.push_back(6692);
        terms.push_back(6908);
        terms.push_back(7987);
        vector<int> ret;
        getBoolSearchRet(terms, ret);
        print(ret);
    } catch( DBException &e ) {
        cout << "caught " << e.what() << endl;
    }
    return 0;
}
void getBoolSearchRet(const vector<int> &terms, vector<int> &ret, 
        const string mongodbCollection, const string host) {
    DBClientConnection c;
    BSONObj p;
    c.connect(host);
    mongo::BSONArrayBuilder b;
    vector<int>::const_iterator it;
    for (it = terms.begin(); it != terms.end(); ++it) {
        b.append(*it);
    }
    BSONObj filter = BSON("id" << BSON("$in" << b.arr()));
    auto_ptr<mongo::DBClientCursor> cursor = c.query(mongodbCollection, filter);  
    int count = 0;
    //first merge, then unique
    while (cursor->more()) {  
        count++;  
        BSONObj obj = cursor->next();  
        std::vector<int> ints;
        obj.getObjectField("relatedDoc").Vals(ints); // asserts on non int values
        std::copy(ints.begin(), ints.end(), std::back_inserter(ret));
        //print(ints);
        //obj = obj.getOwned();
        //cout << "_id:" << obj["_id"].OID().toString() << "******  end  ******"<< endl;
    }
    sort(ret.begin(), ret.end());
    it = unique (ret.begin(), ret.end()); 
    ret.resize(it - ret.begin()); 
    //print(ret);
    //cout << "get " << count << " results!" << endl;
}

